package com.example.safeassistan.home.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.safeassistan.R;
import com.example.safeassistan.base.BaseActivity;
import com.example.safeassistan.base.BaseModel;
import com.example.safeassistan.constants.UrlConstants;
import com.example.safeassistan.hiddendanger.activity.HiddenDangerImageAdapter;
import com.example.safeassistan.hiddendanger.activity.HiddendangerUnSubmit;
import com.example.safeassistan.http.HttpRequest;
import com.example.safeassistan.http.HttpStringCallBack;
import com.example.safeassistan.utile.GlideEngine;
import com.example.safeassistan.utile.JsonUtils;
import com.example.safeassistan.utile.ToastUtil;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class DeviceRepairEdit extends BaseActivity implements View.OnClickListener {
    private static final Integer REQUESTCODE=10001;
    private TextView tvSubmit,tvDeviceName,tvCheckPerson;
    private LinearLayout llCheckPerson;
    private RecyclerView rcPic;
    private EditText etStatus;
    private String deviceId="";//设备id
    private String personId="";//审核人
    private String state="";//问题描述
    private String maintainImg="";//维修图片
    private String title="";//标题


    private HiddenDangerImageAdapter adapter;
    private ArrayList<String> imagesUrl;
    private RecyclerView.LayoutManager managers;

    public static void actionStart(Context context,String deviceId,String title) {
        Intent intent = new Intent(context, DeviceRepairEdit.class);
        intent.putExtra("deviceId",deviceId);
        intent.putExtra("title",title);
        context.startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tvSubmit1:
                if (personId.equals("")){
                    Toast.makeText(DeviceRepairEdit.this,"请选择审核人员！！",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (imagesUrl.size()<=0){
                    Toast.makeText(DeviceRepairEdit.this,"请上传至少一个附件！！",Toast.LENGTH_SHORT).show();
                    return;
                }

                uploadImg(imagesUrl.get(0));
                break;
            case R.id.llCheckPerson:
                //审核人
                Intent intent=new Intent(DeviceRepairEdit.this, ActivityUserList.class);
                intent.putExtra("flag", REQUESTCODE);
                startActivityForResult(intent, REQUESTCODE);
                break;
        }
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setAndroidNativeLightStatusBar(true);
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_device_repair;
    }

    @Override
    protected void initView() {
        setTitleText("报修");
        title=getIntent().getStringExtra("title");
        deviceId=getIntent().getStringExtra("deviceId");
        tvDeviceName=findViewById(R.id.tvDeviceName);
        tvCheckPerson=findViewById(R.id.tvCheckPerson);
        llCheckPerson=findViewById(R.id.llCheckPerson);
        etStatus=findViewById(R.id.etStatus);
        tvSubmit=findViewById(R.id.tvSubmit1);
        rcPic=findViewById(R.id.rcPic);

        tvSubmit.setOnClickListener(this::onClick);
        llCheckPerson.setOnClickListener(this::onClick);
        etStatus.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                state=s.toString().trim();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        tvDeviceName.setText(title);
        imagesUrl=new ArrayList<>();
        managers=new GridLayoutManager(getContext(),3);
        rcPic.setLayoutManager(managers);
        adapter=new HiddenDangerImageAdapter(imagesUrl, DeviceRepairEdit.this);
        rcPic.setHasFixedSize(true);
        rcPic.setAdapter(adapter);
        adapter.setClickListener(new HiddenDangerImageAdapter.OnItemClickListener() {
            @Override
            public void onClick(View view, int position) {
                //添加
                PictureSelector
                        .create(DeviceRepairEdit.this)
                        .openGallery(PictureMimeType.ofImage())
                        .selectionMode(PictureConfig.MULTIPLE)
                        .isCamera(true)
                       // .selectionData(imagesUrl)
                        .maxSelectNum(3)
                        .compressQuality(100)
                        .loadImageEngine(GlideEngine.createGlideEngine())
                        .forResult(PictureConfig.CHOOSE_REQUEST);
            }

            @Override
            public void onSelected(View view, int position) {
                switch (view.getId()){
                    case R.id.ivClear:
                        //删除当前图片
                        imagesUrl.remove(position);
                        adapter.notifyDataSetChanged();
                        break;
                }
            }
        });
    }


    public void uploadImg(String path){
        new HttpRequest(DeviceRepairEdit.this).doUploadFile(UrlConstants.commonupload, "", "file", new File(path), new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Object obj = JsonUtils.fromJson(result.toString(), BaseModel.class);
                        if (obj instanceof BaseModel) {
                            BaseModel model=(BaseModel) obj;
                            imagesUrl.remove(0);
                            maintainImg=maintainImg+model.getMessage()+",";
                            Iterator<String> iterator=imagesUrl.iterator();
                            if (iterator.hasNext()){
                                uploadImg(iterator.next());
                            }else {
                                deviceUntie();
                            }
                        }else {
                            ToastUtil toastUtil = new ToastUtil(getContext(), R.layout.popu_success1, message, 1);
                            toastUtil.show();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) { }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==RESULT_OK){
            if (requestCode==REQUESTCODE){
                personId=data.getStringExtra("id");
                tvCheckPerson.setText(data.getStringExtra("name"));
            } else if (requestCode== PictureConfig.CHOOSE_REQUEST) {
                // 结果回调
                //获取oss  token
                List<LocalMedia> cameraList = PictureSelector.obtainMultipleResult(data);
                imagesUrl.clear();
                for (int i = 0; i < cameraList.size(); i++) {
                    imagesUrl.add(cameraList.get(i).getRealPath());
                }
                adapter.notifyDataSetChanged();
            }
        }
    }

    //获取数据
    public void deviceUntie(){
        JSONObject map = new JSONObject();
        try {
            map.put("deviceId", deviceId);
            map.put("personId",personId);
            map.put("state",state);
            map.put("maintainImg",maintainImg.substring(0,maintainImg.length()-1));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new HttpRequest(DeviceRepairEdit.this).doPost(UrlConstants.taskdeviceMaintain, null, map, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Object obj = JsonUtils.fromJson(result.toString(), BaseModel.class);
                            finish();
                    }else {
                        Toast.makeText(DeviceRepairEdit.this,message,Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    protected int getTitleBarType() {
        return 0;
    }
}
